package org.outlook.xnotepad.action;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.text.JTextComponent;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

/**
 * function:
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-12-23
 */
public class CommandAction extends AbstractAction {

	private static final long serialVersionUID = -7552571146341172876L;
	
	private JLabel messager;
	private JTextComponent editor;

	public CommandAction() {
		super("Command");
	}

	public CommandAction(JLabel messager, JTextComponent editor) {
		super("Command");
		this.messager = messager;
		this.editor=editor;
	}

//	@Override
	public void actionPerformed(ActionEvent e) {
		String commandStr=StringUtils.isBlank(editor.getSelectedText())?editor.getText():editor.getSelectedText();
		BufferedReader bufferedReader;
		try {
			String osName = System.getProperty("os.name");
			boolean isWindows=false;
			if(osName.contains("Windows")) {
				isWindows=true;
			} else {
				isWindows=false;
			}
			final String fileName = getFileName(isWindows);
			File file = new File(fileName);
			FileUtils.writeStringToFile(file, commandStr);
			Process processId = Runtime.getRuntime().exec(fileName);
			if (processId != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(processId.getInputStream()), 1024);
				String line = null;
				StringBuffer sb = new StringBuffer();
				int times=0;
				while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
//					sb.append(line).append(System.getProperty("line.separator"));
					if(times++>1)
						sb.append(line).append("\t\t");
				}
				messager.setText(sb.insert(0, "命令执行结果:").toString());
			}
			FileUtils.deleteQuietly(file);
		} catch (IOException ee) {
			ee.printStackTrace();
			messager.setText("命令执行出错，请检查！");
		}
	}

	private String getFileName(boolean isWindows) {
		return System.getProperty("java.io.tmpdir")+"tmp-"+System.currentTimeMillis()+"."+(isWindows?"bat":"sh");
	}

}